﻿
namespace HSS.Xaml.UI.Controls
{
	#region Using Directives
	using System;
	using System.Windows;
	using System.Windows.Controls;
	using HSS.ComponentModel;
	#endregion

	#region DateTimeValueEditor
	/// <summary>
	/// A <see cref="PropertyGridEditor"/> for <see cref="DateTime"/> instances.
	/// </summary>
	public sealed class DateTimeValueEditor : PropertyGridEditor
	{
		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="descriptor">The <see cref="HSSPropertyDescriptor"/> to be edited.</param>
		public DateTimeValueEditor(HSSPropertyDescriptor descriptor)
			: base(descriptor)
		{
			this.DefaultStyleKey = typeof(DateTimeValueEditor);
		}
		#endregion

		#region Properties
		/// <summary>
		/// Gets the value editor Control
		/// </summary>
		public DatePicker Control
		{
			get { return (DatePicker)base.InlineEditControl; }
		}
		#endregion

		#region Overrides
		/// <summary>
		/// Creates the Inline Editor control.
		/// </summary>
		/// <returns>The control as a FrameworkElement.</returns>
		protected override FrameworkElement CreateInlineEditControl()
		{
			return new DatePicker
			{
				Margin = new Thickness(0),
				Padding = new Thickness(0),
				Height = 18,
				BorderThickness = new Thickness(0),
				VerticalAlignment = VerticalAlignment.Center,
				HorizontalAlignment = HorizontalAlignment.Stretch
			};
		}
		/// <summary>
		/// Updates the editor with the new value.
		/// </summary>
		/// <param name="newValue">The new value.</param>
		protected override void UpdateInlineEditControl(object newValue)
		{
			var time = (DateTime)newValue;
			this.Control.SelectedDate = new DateTime?(time);
		}
		/// <summary>
		/// Gets the current value held by the control.
		/// </summary>
		/// <returns>The object.</returns>
		protected override object GetControlValue()
		{
			if (this.Control.SelectedDate.HasValue)
				return this.Control.SelectedDate.Value;
			else
				return null;
		}
		/// <summary>
		/// Begin the editing process.
		/// </summary>
		protected override void OnBeginEdit()
		{
			base.OnBeginEdit();
			this.Control.CalendarClosed += new RoutedEventHandler(_valueEditor_CalendarClosed);
		}
		/// <summary>
		/// End the editing process.
		/// </summary>
		protected override void OnEndEdit()
		{
			base.OnEndEdit();
			this.Control.CalendarClosed -= new RoutedEventHandler(_valueEditor_CalendarClosed);
		}

		#endregion

		#region Event Handlers
		void _valueEditor_CalendarClosed(object sender, RoutedEventArgs e)
		{
			this.EndEdit();
		}
		#endregion
	}
	#endregion
}
